<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布订阅模式</title>
</head>
<body>
    <script>
        //事件触发器
        class EventEmitter {
            //构造函数
            constructor () {
                //创建一个空的对象
                // {'click':[fn1,fn2],'change':[fn1]}
                this.subs = Object.create(null)
            }
            //注册事件
            //eventType事件类型，handler处理函数
            $on(eventType,handler){
                this.subs[eventType]=this.subs[eventType]||[]
                this.subs[eventType].push(handler)

            }
            //监听事件
            $emit(eventType){
                if(this.subs[eventType]){
                    this.subs[eventType].forEach(handler => {
                        handler()
                    })
                }
            }

        }
        //测试
        let bus = new EventEmitter()
        //注册事件
        bus.$on('click',()=>{
            console.log('click1');
        })
        bus.$on('click',()=>{
            console.log('click2');
        })
        //触发事件
        bus.$emit('click')
    </script>
</body>
</html>